package com.yc.thread.pc;

// 实现一个简单的生产者和消费者模型
public class ProductConsumer {
    public static void main(String[] args){
        Source s = new Source();
        // 线程A 生产
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    s.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "A").start();

        // 线程B 消费
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    s.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "B").start();
    }
}

// 定义资源
class Source{
    private int number = 0;

    // 生产
    public synchronized void increment() throws InterruptedException {
        // if 的判断会产生虚假唤醒问题
//        if (number != 0) {
//            this.wait();
//        }
        while (number != 0) {
            this.wait();
        }
        number ++;
        System.out.println(Thread.currentThread().getName() + "生产了！存货为：" + number);
        this.notifyAll();
    }
    // 消费
    public synchronized void decrement() throws InterruptedException {
//        if (number == 0) {
//            this.wait();
//        }

        while (number == 0) {
            this.wait();
        }
        number --;
        System.out.println(Thread.currentThread().getName() + "消费了！存货为：" + number);
        this.notifyAll();
    }
}
